package org.jeecg.modules.wmhb.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.SysDepartModel;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 销售出库
 * @Author: jeecg-boot
 * @Date: 2024-08-31
 * @Version: V1.0
 */
@Api(tags = "销售出库")
@RestController
@RequestMapping("/wmhb/wmProductSale")
@Slf4j
public class WmProductSaleController extends JeecgController<WmProductSale, IWmProductSaleService> {
    @Autowired
    private IWmProductSaleService wmProductSaleService;
    @Autowired
    private IWmProductRecptService wmProductRecptService;
    @Autowired
    private IWmTaskService wmTaskService;
    @Autowired
    private IWmTaskbookService wmTaskbookService;
    @Autowired
    private IWmTaskFlowService wmTaskFlowService;
    @Autowired
    private IWmFlowDeptService wmFlowDeptService;
    @Autowired
    ISysBaseAPI sysBaseApi;
    @Autowired
    private IWmTaskLogService wmTaskLogService;

    /**
     * 分页列表查询
     *
     * @param wmProductSale
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "销售出库-分页列表查询")
    @ApiOperation(value = "销售出库-分页列表查询", notes = "销售出库-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WmProductSale>> queryPageList(WmProductSale wmProductSale,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                      HttpServletRequest req) {
        QueryWrapper<WmProductSale> queryWrapper = QueryGenerator.initQueryWrapper(wmProductSale, req.getParameterMap());
        Page<WmProductSale> page = new Page<WmProductSale>(pageNo, pageSize);
        IPage<WmProductSale> pageList = wmProductSaleService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param wmProductSale
     * @return
     */
    @AutoLog(value = "销售出库-添加")
    @ApiOperation(value = "销售出库-添加", notes = "销售出库-添加")
    @RequiresPermissions("wmhb:wm_product_sale:add")
    @PostMapping(value = "/add")
    @Transactional
    public Result<String> add(@RequestBody WmProductSale wmProductSale) {
        WmTask wmTask = wmTaskService.getById(wmProductSale.getWmTaskId());
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_PRODUCED);
        statusList.add(UserConstant.TASK_STATUS_SALED);
        statusList.add(UserConstant.TASK_STATUS_WAIT_DEBUG);
        statusList.add(UserConstant.TASK_STATUS_DEBUGING);
        statusList.add(UserConstant.TASK_STATUS_DEBUGED);
        statusList.add(UserConstant.TASK_STATUS_ARRIVED);
        statusList.add(UserConstant.TASK_STATUS_FINISHED);
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);

        //获取事业部信息
        SysDepartModel sysDepartModel = sysBaseApi.selectAllById(wmTask.getBuId());
        if(wmTask.getType().equals(UserConstant.TASK_TYPE_SELF) && !StringUtils.isEmpty(sysDepartModel.getProductWarehouseId())) {
            wmProductSale.setWarehouseId(sysDepartModel.getProductWarehouseId());
        }
        else if(wmTask.getType().equals(UserConstant.TASK_TYPE_BUY) && !StringUtils.isEmpty(sysDepartModel.getVendorWarehouseId())) {
            wmProductSale.setWarehouseId(sysDepartModel.getVendorWarehouseId());
        }
        else if(wmTask.getType().equals(UserConstant.TASK_TYPE_OUT) && !StringUtils.isEmpty(sysDepartModel.getOutSourceWarehouseId())) {
            wmProductSale.setWarehouseId(sysDepartModel.getOutSourceWarehouseId());
        }
        wmProductSale.setStatus(UserConstant.PRODUCT_SALE_STATUS_PREPARE);

        //新的出库数量
        Double newCompleteNum = wmProductSale.getCompleteQuantity() + wmTask.getSaleNum();
        Double remainNum = wmTask.getQuantity() - newCompleteNum;
        if (newCompleteNum > wmTask.getCompleteNum()) {
            throw new RuntimeException("出库数量不能大于剩余数量");
        }

        if (newCompleteNum > wmTask.getQuantity()) {
            throw new RuntimeException("出库数量不能大于设计数量");
        }

        if (newCompleteNum.equals(wmTask.getQuantity())) {
            //如果数量达到出库完成，需要判断子任务是否还有在生产状态，如果有则不能出库完成
            for(WmTask wmTaskItem: wmTaskList){
                if(!statusList.contains(wmTaskItem.getStatus()) && !wmTaskItem.getId().equals(wmTask.getId())){
                    throw new RuntimeException("当前任务有子任务未完成生产");
                }
            }
            wmTask.setProgress("70");//出库完成算70%
            wmTask.setStatus(UserConstant.TASK_STATUS_SALED);//以出库完毕

            //如果当前任务为根任务，任务书状态改为和根任务状态一致
            if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
                WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
                wmTaskbook.setStatus(wmTask.getStatus());
                wmTaskbook.setProgress("70");//出库完成算70%
                wmTaskbookService.updateById(wmTaskbook);
            }

            //获取所有子任务(包括自己)，将子任务状态设置未已出库完成
            for(WmTask wmTaskItem: wmTaskList){
                if(!wmTaskItem.getId().equals(wmTask.getId())){
                    wmTaskItem.setStatus(UserConstant.TASK_STATUS_SALED);//出库完毕
                    wmTaskItem.setProgress("70");//出库完成算70%
                    wmTaskItem.setSaleNum(wmTaskItem.getQuantity());
                    wmTaskService.updateById(wmTaskItem);

                    //新增出库记录
                    WmProductSale wmProductSaleChild = new WmProductSale();
                    wmProductSaleChild.setWmTaskId(wmTaskItem.getId());
                    wmProductSaleChild.setCompleteQuantity(wmTaskItem.getQuantity() - wmTaskItem.getSaleNum());
                    wmProductSaleChild.setRemainQuantity(0D);
                    if(wmTaskItem.getType().equals(UserConstant.TASK_TYPE_SELF) && !StringUtils.isEmpty(sysDepartModel.getProductWarehouseId())) {
                        wmProductSaleChild.setWarehouseId(sysDepartModel.getProductWarehouseId());
                    }
                    else if(wmTaskItem.getType().equals(UserConstant.TASK_TYPE_BUY) && !StringUtils.isEmpty(sysDepartModel.getVendorWarehouseId())) {
                        wmProductSaleChild.setWarehouseId(sysDepartModel.getVendorWarehouseId());
                    }
                    else if(wmTaskItem.getType().equals(UserConstant.TASK_TYPE_OUT) && !StringUtils.isEmpty(sysDepartModel.getOutSourceWarehouseId())) {
                        wmProductSaleChild.setWarehouseId(sysDepartModel.getOutSourceWarehouseId());
                    }
                    wmProductSaleChild.setStatus(UserConstant.PRODUCT_SALE_STATUS_PREPARE);
                    wmProductSaleService.save(wmProductSaleChild);
                }
            }

            //只有设计起点任务才更新日志
            if(wmTask.getIsStartPoint().equals(UserConstant.SYS_YES)) {
                //更新任务日志
                wmTaskLogService.updateTaskLog(wmTask.getId(), UserConstant.TASK_LOG_TYPE_SEND);
            }
        }
        else{
            //处于列表里面状态的都可以出库，不在列表状态的不可以出库
            statusList.add(UserConstant.TASK_STATUS_PRODUCING);
            for(WmTask wmTaskItem: wmTaskList){
                if(!statusList.contains(wmTaskItem.getStatus()) && !wmTaskItem.getId().equals(wmTask.getId())){
                    throw new RuntimeException("当前任务有子任务未完成生产");
                }
            }
        }

        wmTask.setSaleNum(newCompleteNum);
        wmTaskService.updateById(wmTask);

        //出库记录
        wmProductSale.setRemainQuantity(remainNum);
        wmProductSaleService.save(wmProductSale);

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wmProductSale
     * @return
     */
    @AutoLog(value = "销售出库-编辑")
    @ApiOperation(value = "销售出库-编辑", notes = "销售出库-编辑")
    @RequiresPermissions("wmhb:wm_product_sale:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> edit(@RequestBody WmProductSale wmProductSale) {
        WmTask wmTask = wmTaskService.getById(wmProductSale.getWmTaskId());
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);

        //获取事业部信息
        SysDepartModel sysDepartModel = sysBaseApi.selectAllById(wmTask.getBuId());
        if(wmTask.getType().equals(UserConstant.TASK_TYPE_SELF) && !StringUtils.isEmpty(sysDepartModel.getProductWarehouseId())) {
            wmProductSale.setWarehouseId(sysDepartModel.getProductWarehouseId());
        }
        else if(wmTask.getType().equals(UserConstant.TASK_TYPE_BUY) && !StringUtils.isEmpty(sysDepartModel.getVendorWarehouseId())) {
            wmProductSale.setWarehouseId(sysDepartModel.getVendorWarehouseId());
        }
        else if(wmTask.getType().equals(UserConstant.TASK_TYPE_OUT) && !StringUtils.isEmpty(sysDepartModel.getOutSourceWarehouseId())) {
            wmProductSale.setWarehouseId(sysDepartModel.getOutSourceWarehouseId());
        }

        //新的出库数量
        WmProductSale wmProductSaleRecord = wmProductSaleService.getById(wmProductSale.getId());
        Double newCompleteNum = wmProductSale.getCompleteQuantity() + wmTask.getSaleNum() - wmProductSaleRecord.getCompleteQuantity();
        Double remainNum = wmTask.getQuantity() - newCompleteNum;

        if (newCompleteNum > wmTask.getCompleteNum()) {
            throw new RuntimeException("出库数量不能大于剩余数量");
        }

        if (newCompleteNum > wmTask.getQuantity()) {
            throw new RuntimeException("出库数量不能大于设计数量");
        }

        if (newCompleteNum.equals(wmTask.getQuantity())) {
            wmTask.setProgress("70");//出库完成算70%
            wmTask.setStatus(UserConstant.TASK_STATUS_SALED);//以出库完毕

            //如果当前任务为根任务，任务书状态改为和根任务状态一致
            if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
                WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
                wmTaskbook.setStatus(wmTask.getStatus());
                wmTaskbook.setProgress("70");//出库完成算70%
                wmTaskbookService.updateById(wmTaskbook);
            }

            //获取所有子任务(包括自己)，将子任务状态设置未已出库完成
            for(WmTask wmTaskItem: wmTaskList){
                if(!wmTaskItem.getId().equals(wmTask.getId())){
                    wmTaskItem.setStatus(UserConstant.TASK_STATUS_SALED);//出库完毕
                    wmTaskItem.setProgress("70");//出库完成算70%
                    wmTaskItem.setSaleNum(wmTaskItem.getQuantity());
                    wmTaskService.updateById(wmTaskItem);

                    //新增出库记录
                    WmProductSale wmProductSaleChild = new WmProductSale();
                    wmProductSaleChild.setWmTaskId(wmTaskItem.getId());
                    wmProductSaleChild.setCompleteQuantity(wmTaskItem.getQuantity() - wmTaskItem.getSaleNum());
                    wmProductSaleChild.setRemainQuantity(0D);
                    if(wmTaskItem.getType().equals(UserConstant.TASK_TYPE_SELF) && !StringUtils.isEmpty(sysDepartModel.getProductWarehouseId())) {
                        wmProductSaleChild.setWarehouseId(sysDepartModel.getProductWarehouseId());
                    }
                    else if(wmTaskItem.getType().equals(UserConstant.TASK_TYPE_BUY) && !StringUtils.isEmpty(sysDepartModel.getVendorWarehouseId())) {
                        wmProductSaleChild.setWarehouseId(sysDepartModel.getVendorWarehouseId());
                    }
                    else if(wmTaskItem.getType().equals(UserConstant.TASK_TYPE_OUT) && !StringUtils.isEmpty(sysDepartModel.getOutSourceWarehouseId())) {
                        wmProductSaleChild.setWarehouseId(sysDepartModel.getOutSourceWarehouseId());
                    }
                    wmProductSaleChild.setStatus(UserConstant.PRODUCT_SALE_STATUS_PREPARE);
                    wmProductSaleService.save(wmProductSaleChild);
                }
            }

            //只有设计起点任务才更新日志
            if(wmTask.getIsStartPoint().equals(UserConstant.SYS_YES)) {
                //更新任务日志
                wmTaskLogService.updateTaskLog(wmTask.getId(), UserConstant.TASK_LOG_TYPE_SEND);
            }
        }

        wmTask.setSaleNum(newCompleteNum);
        wmTaskService.updateById(wmTask);

        //出库记录
        wmProductSale.setRemainQuantity(remainNum);
        wmProductSaleService.updateById(wmProductSale);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "销售出库-通过id查询")
    @ApiOperation(value = "销售出库-通过id查询", notes = "销售出库-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmProductSale> queryById(@RequestParam(name = "id", required = true) String id) {
        WmProductSale wmProductSale = wmProductSaleService.getById(id);
        if (wmProductSale == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(wmProductSale);
    }

    /**
     * 通过任务ID查询出库记录
     */
    @ApiOperation(value = "销售出库-通过任务ID查询出库记录", notes = "销售出库-通过任务ID查询出库记录")
    @GetMapping(value = "/queryListByWmTaskId")
    public Result<List<WmProductSale>> queryListByWmTaskId(String wmTaskId) {
        List<WmProductSale> wmProductSaleList = wmProductSaleService.queryListByWmTaskId(wmTaskId);
        return Result.OK(wmProductSaleList);
    }

    /**
     * 到货确认
     */
    @AutoLog(value = "销售出库-到货确认")
    @ApiOperation(value = "销售出库-到货确认", notes = "销售出库-到货确认")
    @RequiresPermissions("wmhb:wm_product_sale:arrive")
    @RequestMapping(value = "/arrive", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> doArrive(@RequestParam(name = "ids", required = true) String ids, @RequestParam(name = "wmTaskId", required = true) String wmTaskId) {
        //更新到货状态
        List<String> idList = Arrays.asList(ids.split(","));
        wmProductSaleService.arriveConfirmByIdList(idList);

        //获取任务
        WmTask wmTask = wmTaskService.getById(wmTaskId);
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());

        //获取出库记录信息
        List<WmProductSale> wmProductSaleList = wmProductSaleService.queryListByWmTaskId(wmTaskId);
        Double totalArriveNum = 0D;
        for(WmProductSale wmProductSale: wmProductSaleList){
            if(UserConstant.PRODUCT_SALE_STATUS_ARRIVED.equals(wmProductSale.getStatus())) {
                totalArriveNum = totalArriveNum + wmProductSale.getCompleteQuantity();
            }
        }

        //更新任务状态为已到货和到货数量
        wmTask.setArriveNum(totalArriveNum);
        if(wmTask.getQuantity().equals(totalArriveNum)){
            //获取所有子任务(包括自己)，将子任务状态设置未已到货完成
            List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);
            for(WmTask wmTaskItem: wmTaskList){
                wmTaskItem.setStatus(UserConstant.TASK_STATUS_ARRIVED);//到货完毕
                wmTaskItem.setProgress("80");//到货完成算80%

                //下一流程(生产和调试在一个大部门，不再区分小组和子部门)
                //nextFlowTask(wmTaskItem);

                //更新任务书当前流程部门
                if(wmTaskItem.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
                    wmTaskbook.setProgress(wmTaskItem.getProgress());
                    wmTaskbook.setStatus(wmTaskItem.getStatus());
                    wmTaskbookService.updateById(wmTaskbook);
                }
            }
        }
        else{
            wmTaskService.updateById(wmTask);
        }
        return Result.OK("操作成功");
    }

    /**
     * 任务下一流程
     * @param wmTask
     * @return
     */
    private void nextFlowTask(WmTask wmTask){
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
        //1、流程部门列表
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());

        //2、下一流程
        Integer nextIndex = wmTask.getCurrentNodeIndex() + 1;
        if(nextIndex >= wmFlowDeptList.size()){
            if(wmTaskbook.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_TECHNOLOGY)){
                //技术服务任务书设计提交后没有下一流程（技术服务设计和调试是一个部门）
                wmTaskService.updateById(wmTask);
                return;
            }
            else{
                throw new RuntimeException("请补充完整的流程定义");
            }
        }

        //3、更改子任务的当前流程节点及时间信息
        WmTaskFlow wmTaskFlowCurr = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), nextIndex - 1);
        WmTaskFlow wmTaskFlowNext = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), nextIndex);
        wmTaskFlowCurr.setFactEndTime(new Date());
        wmTaskFlowNext.setFactBeginTime(new Date());
        wmTaskFlowService.updateById(wmTaskFlowCurr);
        wmTaskFlowService.updateById(wmTaskFlowNext);

        //4、更新子任务当前节点
        wmTask.setCurrentNodeTime(new Date());
        wmTask.setCurrentNodeId(wmFlowDeptList.get(nextIndex).getDeptId());
        wmTask.setCurrentNodeIndex(nextIndex);
        wmTaskService.updateById(wmTask);

        //5、更新任务书当前流程部门
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            wmTaskbook.setCurrentNodeIndex(nextIndex);
            wmTaskbook.setProgress(wmTask.getProgress());
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbook.setCurrentNodeId(wmFlowDeptList.get(nextIndex).getDeptId());
            wmTaskbookService.updateById(wmTaskbook);
        }
    }

    /**
     * 任务上一流程
     * @param wmTask
     * @return
     */
    private void prevFlowTask(WmTask wmTask){
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
        //1、流程部门列表
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());

        //2、上一流程
        Integer prevIndex = wmTask.getCurrentNodeIndex() - 1;
        if(prevIndex < 0){
            throw new RuntimeException("流程异常");
        }

        //3、更改子任务的当前流程节点及时间信息
        WmTaskFlow wmTaskFlowPrev = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), prevIndex);
        WmTaskFlow wmTaskFlowCurr = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), prevIndex + 1);
        wmTaskFlowPrev.setFactEndTime(null);
        wmTaskFlowCurr.setFactBeginTime(null);
        wmTaskFlowService.updateById(wmTaskFlowPrev);
        wmTaskFlowService.updateById(wmTaskFlowCurr);

        //4、更新子任务当前节点
        wmTask.setCurrentNodeTime(new Date());
        wmTask.setCurrentNodeId(wmFlowDeptList.get(prevIndex).getDeptId());
        wmTask.setCurrentNodeIndex(prevIndex);
        wmTaskService.updateById(wmTask);

        //5、更新任务书当前流程部门
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            wmTaskbook.setProgress(wmTask.getProgress());
            wmTaskbook.setCurrentNodeIndex(prevIndex);
            wmTaskbook.setCurrentNodeId(wmFlowDeptList.get(prevIndex).getDeptId());
            wmTaskbookService.updateById(wmTaskbook);
        }
    }
}
